package com.example.parking.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.parking.dto.Result;
import com.example.parking.entity.Order;
import com.example.parking.mapper.OrderMapper;
import com.example.parking.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/statistics")
@CrossOrigin
public class StatisticsController {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private IOrderService orderService;

    /**
     * 分页查询所有已完成的订单-管理员统计报表
     * @return
     */
    @GetMapping("/getOrder")
    public Result getOrder(@RequestParam Integer pageNum,
                           @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        Page<Order> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("state",1);
        Page<Order> orderPage = orderService.page(page, wrapper);
        return Result.successData(orderPage);
    }

    /**
     * 按时间区间查询订单信息
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/getOrderByDate")
    public Result getOrderByDate(@RequestParam String beginTime,@RequestParam String endTime){
        if (beginTime.equals("NaN-NaN-NaN NaN:NaN:NaN")){
            List<Order> orderList = orderMapper.getList();
            return Result.successData(orderList);
        }
        List<Order> orderList = orderMapper.getByDate(beginTime, endTime);
        return Result.successData(orderList);
    }

    /**
     * 导出订单报表
     */
    @PostMapping("/exportExcel/{beginTime}/{endTime}")
    public Result ExportExcel(@PathVariable String beginTime,@PathVariable String endTime) {
        // 设置文件导出的路径
        String realPath = "C://Users/Mercy1108/Desktop/";
        File folder = new File(realPath);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String fileName = realPath  + "Order" + System.currentTimeMillis() + ".xlsx";
        if (beginTime.equals("NaN-NaN-NaN NaN:NaN:NaN")){
            EasyExcel.write(fileName, Order.class).sheet("订单表").doWrite(orderMapper.getList());
            return Result.success();
        }
        EasyExcel.write(fileName, Order.class).sheet("订单表").doWrite(orderMapper.getByDate(beginTime, endTime));
        return Result.success();
    }
}
